import json
import re
import time
import asyncio
from urllib.parse import unquote
from bs4 import BeautifulSoup
from fastapi import APIRouter
from spider.spider import Spider
from setting import DY_HEADERS
from comm.rpc import RPC

router = APIRouter()
requests = Spider()
rpc = RPC()


async def do_rpc(params, api):
    uid = await rpc.submit(params, api)
    for i in range(100):
        await asyncio.sleep(1)
        res = await rpc.get(uid)
        if res is not None:
            return res


@router.get('/api/ks/userInfo')
async def ks_user(user_id: str):
    res = await do_rpc({'user_id': user_id}, '/api/ks/userInfo')
    return res


@router.get('/api/ks/video')
async def ks_photo(user_id: str, pcursor: str = None):
    res = await do_rpc({'user_id': user_id, 'pcursor': pcursor}, '/api/ks/video')
    return res


@router.get('/api/dy/userInfo')
async def dy_user(user_id: str):
    search_id = await dy_search(user_id)
    if 'error_msg' in search_id:
        return search_id
    basic_url = 'https://www.douyin.com/user/' + search_id
    basic_html = await requests.get(basic_url, headers=DY_HEADERS)
    basic_html = basic_html.text
    html_obj = BeautifulSoup(basic_html, 'html.parser')
    info_text = html_obj.find_all('script', {'id': 'RENDER_DATA'})[0].string
    render_data = unquote(info_text)
    render_obj = json.loads(render_data)
    render_c = render_obj.get('C_10')
    user = render_c.get('user').get('user')
    fans_count = user['followerCount']  # ��˿
    follow_count = user['followingCount']  # ��ע
    favorite_count = user['totalFavorited']  # ����
    video_num = user['awemeCount']  # ��Ʒ��
    avatar_url = user['avatarUrl']  # 头像链接
    main_url = 'https://www.iesdouyin.com/share/user/59883458109?sec_uid=' + search_id  # 主页链接
    user_dict = {
        'fans_count': fans_count,
        'follow_count': follow_count,
        'favorite_count': favorite_count,
        'video_num': video_num,
        'headurl': avatar_url,
        'main_url': main_url
    }
    return user_dict


@router.get('/api/dy/video')
async def dy_video(user_id: str, page: int = None):
    search_id = await dy_search(user_id)
    if 'error_msg' in search_id:
        return search_id
    basic_url = 'https://www.douyin.com/user/' + search_id
    basic_html = await requests.get(basic_url, headers=DY_HEADERS)
    basic_html = basic_html.text
    html_obj = BeautifulSoup(basic_html, 'html.parser')
    # ��Ƶ����
    a_tags = html_obj.select('a')
    video_list = []
    for tag_a in a_tags:
        while True:
            if not hasattr(tag_a, 'href'):
                break
            share_url = tag_a['href']  # 分享链接
            if not 'video' in share_url:
                break
            video_id = re.findall('video/(.*?)\?', share_url)[0]  # ��ƵΨһid
            detail_url = 'https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=' + video_id
            try:
                video_detail = await requests.get(detail_url)
                video_detail = video_detail.text
                # print("video_detail======" + video_detail)
                detail_obj = json.loads(video_detail)
                item_list = detail_obj.get('item_list')[0]
                create_time = item_list['create_time']  # ����ʱ��
                video_desc = item_list['desc']  # ��Ƶ����
                detail_num = item_list.get('statistics')
                digg_count = detail_num['digg_count']  # ����
                share_count = detail_num['share_count']  # ����
                comment_count = detail_num['comment_count']  # ����
                video = item_list.get('video')
                video_url = video.get('play_addr').get('url_list')[0]  # 视频链接
                cover_url = video.get('origin_cover').get('url_list')[0]  # 封面url
                video_list.append({
                    'video_title': video_desc,
                    'create_time': create_time,
                    'like_count': digg_count,
                    'share_count': share_count,
                    'comment_count': comment_count,
                    'video_url': video_url,
                    'cover_url': cover_url,
                    'video_id': video_id,
                    'share_url': share_url
                })
                break
            except Exception as e:
                print(e)
    return {'video_list': video_list}


async def dy_search(douyin_code: str):
    list_header = {
        'Host': 'search5-search-lf.amemv.com',
        'Connection': 'keep-alive',
        'x-tt-dt': 'AAA2YNQUU4GZOXS4XO52YZPRA46V6YXY2UGIDVCQG5IDSOBOFS6O5Q74JRQ5YG6QOX5UH7KGMMORJVTWA3MW3QLPKGZOI7OVTYFODFSDNILUU63PFUWYM4LQ2RAEUVMD3H34Z6KXWT7I7LNZTUMWPSY',
        'passport-sdk-version': '18',
        'X-Tt-Token': '00ba81c058dbc640f18a73977a165412af06384210a51b42ad80b70064d99a793d2737a8acb79236ed60f81f5ff33b60c4bbf7cab85a0e302f8cd7f5cf72f2b3d660ad92b51d304eba8159464cd92f1d56dec48781cf5b1bec970e82410d437641d5e-1.0.1',
        'sdk-version': '2',
        'X-SS-REQ-TICKET': '1625724913552',
        'x-bd-kmsv': '1',
        'X-SS-DP': '1128',
        'x-tt-trace-id': '00-84c1890d0d6706891fc0eb7979060468-84c1890d0d670689-01',
        'User-Agent': 'com.ss.android.ugc.aweme/150201 (Linux; U; Android 5.1.1; zh_CN; OPPO R11; Build/NMF26X; Cronet/TTNetVersion:539f4bcf 2021-01-18 QuicVersion:47946d2a 2020-10-14)',
        'Accept-Encoding': 'gzip, deflate, br',
        'X-Argus': 'WPsGIbg9bnxEXJvdiarI/iW2CRDwgrNYbzDZko6Rg4ZUCGxfeZB5VE8fKv1GjbWkMMLrszUCKKdChN5Ydg1uu7nhxvbsKOVXtvp0MBdP/yyDq9HNTUpTj5hGJNATgDPJKW9u/d4JaUo5H7cltS5BxunSxdo1NnHy95pCDSn3wxNjoMmFFRpE/CNNztrNRehvHyHOlegbJf82CUtxLP+iH76TATazfFC2bSZKOCkxfTg3TmsjggLdZDeIR/xEiDzO5iOwq6f04NEjHUWN93yVJn0+Hd1KHKWcOkHtbJ1OgUH3Yl9Y1KY8iLcxjIZhH9MrX1tZZLQD0HYu+0GYYwRPuwqWu0V6LGVQNhprD4VohfpeQQ==',
        'X-Gorgon': '04040034000032842aa0dfd0a41f1ce3bcf99d347ccc38daa532',
        'X-Khronos': '1625724913',
        'X-Ladon': 'I0oUIcEAyoszjnMul1WwOaNG29e/7iLVUFuEG8QmmuLTfsq3',
        'X-Tyhon': '7ywXjs1zFIiiVQKogGgSg88FGaeJWB6rslIPFaU=',
        'x-common-params-v2': 'aid=1128&app_name=aweme&app_type=normal&cdid=1660ae69-6ca9-414f-9786-aced194c318d&channel=aweGW&device_brand=OPPO&device_id=1812444288388791&device_platform=android&device_type=OPPO+R11&dpi=320&iid=264341505977773&language=zh&manifest_version_code=150201&mcc_mnc=46007&openudid=58fb840e76da7935&os_api=22&os_version=5.1.1&resolution=900*1600&ssmix=a&update_version_code=15209900&uuid=863254010793494&version_code=150200&version_name=15.2.0'
    }
    list_url = 'https://search5-search-lf.amemv.com/aweme/v1/search/sug/?keyword=' + douyin_code + '&source=general&from_group_id=6980646256297135367&ts=1625724914&cpu_support64=false&appTheme=dark&ac=wifi&host_abi=armeabi-v7a&_rticket=1625724913551&minor_status=0&'
    resp = await requests.get(list_url, headers=list_header)
    item_obj = resp.json
    sug_list = item_obj.get("sug_list")
    for sug in sug_list:
        extra_info = sug["extra_info"]
        extra_info_str = str(extra_info)
        if 'rich_sug_short_id' in extra_info_str:
            rich_sug_short_id = extra_info["rich_sug_short_id"]
            if rich_sug_short_id == douyin_code:
                return extra_info["rich_sug_sec_uid"]
    return {'error_msg': '未找到对应的用户'}
